package com.sx.manage.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.sx.model.constants.MSystemConstants;

import sun.misc.BASE64Encoder;

/**
 * 直销银行-身份证上传
 * @author zwm
 *
 */
public class ImageUtils {
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(ImageUtils.class);
	/**
	 * 按照 宽高 比例压缩
	 * 
	 * @param img
	 * @param width
	 * @param height
	 * @param out
	 * @throws IOException
	 */
	public static void thumbnail_w_h(File img, int width, int height, OutputStream out) throws IOException {
		BufferedImage bi = ImageIO.read(img);
		double srcWidth = bi.getWidth(); // 源图宽度
		double srcHeight = bi.getHeight(); // 源图高度

		double scale = 1;

		if (width > 0) {
			scale = width / srcWidth;
		}
		if (height > 0) {
			scale = height / srcHeight;
		}
		if (width > 0 && height > 0) {
			scale = height / srcHeight < width / srcWidth ? height / srcHeight : width / srcWidth;
		}

		thumbnail(img, (int) (srcWidth * scale), (int) (srcHeight * scale), out);

	}

	/**
	 * 按照固定宽高原图压缩
	 * 
	 * @param img
	 * @param width
	 * @param height
	 * @param out
	 * @throws IOException
	 */
	public static void thumbnail(File img, int width, int height, OutputStream out) throws IOException {
		BufferedImage BI = ImageIO.read(img);
		Image image = BI.getScaledInstance(width, height, Image.SCALE_SMOOTH);

		BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.setColor(Color.RED);
		g.drawImage(image, 0, 0, null); // 绘制处理后的图
		g.dispose();
		ImageIO.write(tag, "JPEG", out);
	}

	/**
	 * 按照宽高裁剪
	 * 
	 * @param srcImageFile
	 * @param destWidth
	 * @param destHeight
	 * @param out
	 */
	public static void cut_w_h(File srcImageFile, int destWidth, int destHeight, OutputStream out) {
		cut_w_h(srcImageFile, 0, 0, destWidth, destHeight, out);
	}

	public static void cut_w_h(File srcImageFile, int x, int y, int destWidth, int destHeight, OutputStream out) {
		try {
			Image img;
			ImageFilter cropFilter;
			// 读取源图像
			BufferedImage bi = ImageIO.read(srcImageFile);
			int srcWidth = bi.getWidth(); // 源图宽度
			int srcHeight = bi.getHeight(); // 源图高度

			if (srcWidth >= destWidth && srcHeight >= destHeight) {
				Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);

				cropFilter = new CropImageFilter(x, y, destWidth, destHeight);
				img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制截取后的图
				g.dispose();
				// 输出为文件
				ImageIO.write(tag, "JPEG", out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}// #cut_w_h
	
	/**
	 * 本地图片转换成base64字符串
	 * @param imgFile	图片本地路径
	 * @return
	 *
	 * @author ZHANGJL
	 * @dateTime 2018-02-23 14:40:46
	 */
	@SuppressWarnings("restriction")
	public static String ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
 
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			
			data = new byte[in.available()];
			in.read(data);
			in.close();
			File file = new File(imgFile);
			if(file.exists()) {
				file.delete();
			}
		} catch (IOException e) {
			log.error("文件复制异常error={}",e);
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}
	
	/**
	 * 老文件文件创建
	 * @param fileName
	 * @return
	 */
	public static String create_temporary_file(String fileName) {
		/** 临时文件夹*/
		String imgPath = "xyimages" + File.separator + "buttonImgTemp" + File.separator;
        String tempPath = MSystemConstants.CERTIMAGEFACE_OLD_PATH + imgPath+fileName;
        System.out.println("old-path-" + tempPath);
        File oldFile = new File(tempPath);
        if (!oldFile.exists()) {
            oldFile.mkdirs();
        }
		return tempPath;
	}
	
	/**
	 * 新文件创建
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String create_new_file(MultipartFile myFile,String fileName) {
		/** 新文件夹*/
		String newImaPath = "xyimages" + File.separator + "buttonImg" + File.separator;
        String tempPath = MSystemConstants.CERTIMAGEFACE_NEW_PATH + newImaPath+fileName;
        File newFile = new File(tempPath);
        if (!newFile.exists()) {
        	newFile.mkdirs();
        }
        InputStream is = null;
        FileOutputStream fs = null;
        try {
	        /** 先存取源文件*/
	        is = myFile.getInputStream();
	        fs = new FileOutputStream(MSystemConstants.CERTIMAGEFACE_OLD_PATH+myFile.getOriginalFilename());
	        //...
	        if (myFile.getSize() > 0) {
	            byte[] buffer = new byte[1024 * 1024];
	            int bytesum = 0;
	            int byteread = 0;
	            while ((byteread = is.read(buffer)) != -1) {
	                bytesum += byteread;
	                fs.write(buffer, 0, byteread);
	                fs.flush();
	            }
	            fs.close();
	            is.close();
	        }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
		
		return tempPath;
	}
	
	
	
	

	public static void main(String[] args) throws IOException {
		File img = new File("D:\\apache-tomcat-8.0.41-manage\\webapps\\manage\\upload\\微信图片_20181031153858.jpg");
		img.getName();
		System.out.println(img.getName());
		FileOutputStream fos = new FileOutputStream("D:\\apache-tomcat-8.0.41-manage\\webapps\\manage\\upload\\123\\微信图片_20181031153858.jpg");
		// ImgTools.thumbnail(img, 100, 100, fos);
		// ImgTools.cut_w_h(img, 230, 200, fos);
		ImageUtils.thumbnail(img, 500, 300, fos);
//		String str = "D:\\apache-tomcat-8.0.41-manage\\webapps\\manage\\upload\\123\\xyimages\\buttonImg\\微信图片_20181031153858.jpg";
		ImageToBase64ByLocal("D:\\\\apache-tomcat-8.0.41-manage\\\\webapps\\\\manage\\\\upload\\\\123\\\\微信图片_20181031153858.jpg");
	}

}
